package com.example.ujsfish.activity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.example.ujsfish.R;
import com.example.ujsfish.model.PathNodes;
import com.example.ujsfish.model.PlanPathBody;
import com.example.ujsfish.model.boundary.BoundaryBody;
import com.example.ujsfish.model.boundary.BoundaryPoint;
import com.example.ujsfish.model.boundary.ObstaclesBody;
import com.example.ujsfish.model.manual.ManualControlData;
import com.example.ujsfish.utils.AppNetService;
import com.example.ujsfish.model.Coordinate;
import com.example.ujsfish.model.MyPoint;
import com.example.ujsfish.model.monitor.Data;
import com.example.ujsfish.model.monitor.JsonRootBean;
import com.example.ujsfish.model.ship.CurrentPlanPath;
import com.example.ujsfish.utils.DeviceName;
import com.example.ujsfish.utils.RetrofitManager;
import com.example.ujsfish.view.*;


import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class CreateMap extends AppCompatActivity {

    private static final String TAG = "CreateMap";
    private Coordinate coordinate = Coordinate.getInstance();
    ArrayList<MyPoint> coordinateList = coordinate.getCoordinateList();


    private ManualControlData.ManualBody manualBody = ManualControlData.getManualBody();


    private CurrentPlanPath currentPlanPath = CurrentPlanPath.getInstance();
    List<MyPoint> pathPointList = currentPlanPath.getPlanPathList();
    List<MyPoint> boundaryPointList = currentPlanPath.getBoundaryList();
    List obsPointList = currentPlanPath.getObstacleList();


    RetrofitManager myRetrofitManager = RetrofitManager.getInstance();
    Retrofit myRetrofit = RetrofitManager.getRetrofit();
    AppNetService appNetService = myRetrofitManager.getApiService(AppNetService.class);
    Timer timer;
    TimerTask task;
    String id = DeviceName.getDeviceInstance().getDeviceId().get(0);

    private Button btn_sizeUp;
    private Button btn_sizeDown;
    private ImageView moveForward;
    private ImageView moveBack;
    private ImageView moveLeft;
    private ImageView moveRight;
    private MyView mv;

    SharedPreferences.Editor mapEditor;
    private SharedPreferences mapPreferences;

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_map_activity);

        SharedPreferences preferences = getSharedPreferences("data",MODE_PRIVATE);
        mapPreferences = getSharedPreferences("mapSet",MODE_PRIVATE);
        mapEditor = mapPreferences.edit();

        String device = preferences.getString("device","");
        String pool = preferences.getString("pool","");
        String path = preferences.getString("path","");
        String userName = preferences.getString("userName","");

        initView();

        //加载池塘边界
        initBoundary(pool,userName);

        //分析边界信息，确定尺度与偏移量
        //analysisBoundary(boundaryPointList);

        //加载障碍点
        initObstacle(pool,userName);

        //加载规划轨迹
        initPath(pool,path,userName);

        //为轨迹添加一个初始零点
        initPoint();

        initMapView();
        //设置mv的大小与位置
        //initMv(mv, mapPreferences);

        ActionBar actionBar = this.getSupportActionBar();
        actionBar.setTitle("轨迹规划");
        actionBar.setDisplayHomeAsUpEnabled(true);

        setViewSize(mv,mapEditor);
        setViewPosition(mv,mapEditor);


        mv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    final EditText text = new EditText(getApplicationContext());
                    text.setText("投饵量：                   |   船速：");

                    final AlertDialog.Builder alterDialog = new AlertDialog.Builder(CreateMap.this);
                    alterDialog.setIcon(R.drawable.ic_launcher_background);
                    alterDialog.setTitle("修改此段投饵参数");
                    alterDialog.setView(text);
                    //alterDialog.setMessage("坐标是" + (int) event.getRawX() + "&&" + event.getY());
                    alterDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });

                    alterDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(CreateMap.this, "修改完成", Toast.LENGTH_SHORT).show();
                        }
                    });
                    alterDialog.show();
                    //Toast.makeText(getApplicationContext(), "坐标是" + (int) event.getX() + "&&" + event.getY(), Toast.LENGTH_SHORT).show();
                }

                return true;
            }
        });
//        Thread t = new Thread(mv);
//        t.start();


    }

    private void initMapView() {
        ConstraintLayout constraintLayout = findViewById(R.id.conlayout2);
        mv = new MyView(this);
        constraintLayout.addView(mv);//添加自定义视图
    }

    private void analysisBoundary(List<MyPoint> boundaryPointList) {
        for (int i = 0; i < boundaryPointList.size() - 1; i++) {
            //boundaryPointList.get(i)
        }

    }

    private void initMv(MyView mv, SharedPreferences mapPreferences) {
        mv.setK(mapPreferences.getInt("size",30));
        mv.setHorizontalMove(mapPreferences.getFloat("horizontalMove",0f));
        mv.setVerticalMove(mapPreferences.getFloat("verticalMove",0f));
        System.out.println("执行了initMv");
        System.out.println(mapPreferences.getInt("size",-1));
        System.out.println(mapPreferences.getFloat("horizontalMove",-1));
        System.out.println(mapPreferences.getFloat("verticalMove",-1));

    }

    private void setViewPosition(MyView mv, SharedPreferences.Editor mapEditor) {
        moveForward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mv.setVerticalMoveUp();
            }
        });

        moveBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mv.setVerticalMoveDown();
            }
        });

        moveLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mv.setHorizontalMoveUp();
            }
        });

        moveRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mv.setHorizontalMoveDown();
            }
        });
        mv.postInvalidate();
//        mapEditor.putFloat("horizontalMove",mv.getHorizontalMove());
//        mapEditor.putFloat("verticalMove",mv.getVerticalMove());
    }

    private void setViewSize(MyView mv, SharedPreferences.Editor mapEditor) {

        btn_sizeUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mv.setKUp();

            }
        });

        btn_sizeDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mv.setKDown();
            }
        });
        mv.postInvalidate();
        //mapEditor.putInt("size",mv.getK());
    }


    private void initView() {
        btn_sizeUp = findViewById(R.id.btn_sizeUp);
        btn_sizeDown = findViewById(R.id.btn_sizeDown);
        moveForward = findViewById(R.id.btn_upMove);
        moveBack = findViewById(R.id.btn_downMove);
        moveLeft = findViewById(R.id.btn_leftMove);
        moveRight = findViewById(R.id.btn_rightMove);

    }

    private void moveControl() {
        manualBody.clear();
        //手动控制指令
        moveForward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                manualBody.setLeftWheelAdd();
                manualBody.setRightWheelAdd();
                sendManualCm(id);
            }
        });

        moveBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                manualBody.setLeftWheelDelete();
                manualBody.setRightWheelDelete();
                sendManualCm(id);
            }
        });

        moveLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                manualBody.setRightWheelAdd();
                sendManualCm(id);

            }
        });

        moveRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                manualBody.setLeftWheelAdd();
                sendManualCm(id);
            }
        });


    }

    private void sendManualCm(String id) {
        manualBody.setDevice_name(id);
        Log.d(TAG, "sendManualCm: " + manualBody.toString());
        Call<ResponseBody> call = appNetService.postManualControl(manualBody);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Log.d(TAG, "onResponse: " + response);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

    //将从服务器获取的规划点存入集合
    private void initPath(String pool, String path, String userName) {
        Call<PlanPathBody> planPathBodyCall = appNetService.postFindPathBU(pool,path,userName);
        planPathBodyCall.enqueue(new Callback<PlanPathBody>() {
            @Override
            public void onResponse(Call<PlanPathBody> call, Response<PlanPathBody> response) {
                PlanPathBody planPathBody = response.body();
                List<PathNodes> planPathList = planPathBody.getData().getPathNodes();
                System.out.println(planPathList.toString());
                //使用foreach
                pathPointList.clear();
                for (PathNodes pathNodes : planPathList
                ) {
                    pathPointList.add(new MyPoint(pathNodes.getCoord_x(),pathNodes.getCoord_y()));
                }
                //currentPlanPath.setPlanPathList((ArrayList<MyPoint>) pathPointList);
            }

            @Override
            public void onFailure(Call<PlanPathBody> call, Throwable t) {

            }
        });


    }

    private void initObstacle(String pool, String userName) {
        Call<ObstaclesBody> obstaclesBodyCall = appNetService.postFindObstaclesPointsBU(pool,userName);
        obstaclesBodyCall.enqueue(new Callback<ObstaclesBody>() {
            @Override
            public void onResponse(Call<ObstaclesBody> call, Response<ObstaclesBody> response) {
                ObstaclesBody obstaclesBody = response.body();
                System.out.println("obstaclesBody is" +obstaclesBody.getData().toString());

                    List obsList = obstaclesBody.getObs();
                    obsPointList.clear();
                    obsPointList.addAll(obsList);
                    Log.d(TAG, "obsPointList" + obsPointList.toString());


            }
            @Override
            public void onFailure(Call<ObstaclesBody> call, Throwable t) {

            }
        });


    }


    private void initBoundary(String pool, String userName) {
        Call<BoundaryBody> boundaryBodyCall = appNetService.postFindBoundaryBU(pool,userName);
        boundaryBodyCall.enqueue(new Callback<BoundaryBody>() {
            @Override
            public void onResponse(Call<BoundaryBody> call, Response<BoundaryBody> response) {
                BoundaryBody boundaryBody = response.body();

                try {
                    BoundaryPoint boundaryPoint = boundaryBody.getData();
                    String points = boundaryPoint.getPoints();
                    //将解析好的边界点存入单例
                    boundaryPointList.clear();
                    boundaryPointList.addAll(praiseBoundaryPoint(points));
                    Log.d(TAG, "boundaryPointList: " + boundaryPointList.toString());
                    Log.d(TAG, "praiseBoundaryPoint: " + praiseBoundaryPoint(points).toString());

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    System.out.println(boundaryBody.toString());
                }

            }

            private List<MyPoint> praiseBoundaryPoint(String point) {
                List<MyPoint> boundaryPointList = new ArrayList<>();
                String[] split = point.split(";");
                for (int i = 0; i < split.length; i++) {
                    String[] split1 = split[i].split(",");
                    String x = split1[0];
                    String y = split1[1];
                    boundaryPointList.add(new MyPoint(x,y));
                }
                return boundaryPointList;
            }

            @Override
            public void onFailure(Call<BoundaryBody> call, Throwable t) {

            }
        });


    }


    private void initPoint() {
        coordinateList.add(new MyPoint(0f,0f));

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == android.R.id.home)
        {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void updateView(AppNetService appNetService) {
        Call<JsonRootBean> call1 = appNetService.postMonitor(id);
        call1.enqueue(new Callback<JsonRootBean>() {
            @Override
            public void onResponse(Call<JsonRootBean> call, Response<JsonRootBean> response) {
                System.out.println(response.toString());
                if (response.body().getData().size() != 0) {
                    JsonRootBean jsonRootBean = response.body();
                    Data monitorData = jsonRootBean.getData().get(0);
                    coordinateList.add(new MyPoint(monitorData.getX_coordinate(), monitorData.getY_coordinate()));
                    mv.postInvalidate();
                    System.out.println("接收到的点为：" + monitorData.getX_coordinate() + monitorData.getY_coordinate());
                }
            }

            @Override
            public void onFailure(Call<JsonRootBean> call, Throwable t) {
                Log.d(TAG, "onFailure: " + t.toString());
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                updateView(appNetService);
            }
        };
        timer.schedule(task,0,1000);
        initMv(mv,mapPreferences);
        System.out.println("定时器开启");


    }


    @Override
    protected void onPause() {
        super.onPause();
        timer.cancel();
        System.out.println("定时器关闭");

        mapEditor.putInt("size",mv.getK());
        mapEditor.putFloat("horizontalMove",mv.getHorizontalMove());
        mapEditor.putFloat("verticalMove",mv.getVerticalMove());
        mapEditor.apply();
        System.out.println(mv.getK());
        System.out.println(mv.getHorizontalMove());
        System.out.println(mv.getVerticalMove());

    }





}
